<?php


namespace App\Models;


use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;

class UsersLoginLog extends Model
{
    protected $table = 'users_login_log_01';
    protected $tableStr = 'users_login_log_';
    public $timestamps = false; // 指示模型是否自动维护时间戳
    protected $dateFormat = 'U'; // 模型日期列的存储格式。

    protected function tables(){
        return array(
            'users_login_log_01',
            'users_login_log_02',
            'users_login_log_03',
            'users_login_log_04',
            'users_login_log_05',
            'users_login_log_06',
        );
    }

    /**
     * Todo:: 获取表名称
     * @param $userId
     * @return bool|int|string
     */
    public function tableName($userId){
        $num = $userId%6;
        $string = $this->tableStr;
        if($num>0 && $num < 10){
            $string .= '0'.$num;
        }elseif($num > 10){
            $string .= $num;
        }
        if(in_array($string,$this->tables())){
            $this->table = $string;
            return $string;
        }
        return false;
    }

    /**
     * Todo:: 类型 组
     * @param string $code
     * @return array|mixed|null
     */
    public function typeArr($code=''){
        $data = [
            0 => '未知',
            1 => '注册',
            2 => '登录',
            3 => '登出',
        ];
        if($code){
            return isset($data[$code])?$data[$code]:null;
        }
        return $data;
    }

    /**
     * Todo:: 添加用户记录信息
     * @param $userId
     * @param $data
     * @return int
     */
    public function addData($userId,$data){
        $this->tableName($userId);
        $insert = DB::table($this->table)->insertGetId([
            'user_id' => $userId,
            'type' => isset($data['type'])?$data['type']:0,
            'ip' => isset($data['ip'])?$data['ip']:'0.0.0.0',
            'source_id' => isset($data['source_id'])?$data['source_id']:0,
            'source_ip' => isset($data['source_ip'])?$data['source_ip']:'0.0.0.0',
            'remark' => isset($data['remark'])?$data['remark']:'not',
        ]);
        return $insert;
    }

    /**
     * Todo:: 获取登录日志
     * @param $userId
     * @param array $conditions
     * @param int $page
     * @param int $pageSize
     * @return \Illuminate\Contracts\Pagination\LengthAwarePaginator|\Illuminate\Database\Query\Builder
     */
    public function userLists($userId,$conditions=[],$page=1,$pageSize=10){
        $this->tableName($userId);
        $lists = DB::table("{$this->table} as log")->leftJoin('platform','log.source_id','=','platform.id')
            ->where('log.user_id',$userId);
        if (isset($conditions['type']) && !empty($conditions['type'])) {
            $lists->where('log.type', $conditions['type']);
        }
        if (isset($conditions['source_id']) && !empty($conditions['source_id'])) {
            $lists->where('log.source_id', $conditions['source_id']);
        }

        if (isset($conditions['start_time']) && !empty($conditions['start_time']) && isset($conditions['end_time']) && !empty($conditions['end_time'])) {
            $lists->whereBetween('log.created_at', [$conditions['start_time'],$conditions['end_time']]);
        }else{
            if(isset($conditions['start_time']) && !empty($conditions['start_time'])){
                $lists->where('log.created_at','>',$conditions['start_time']);
            }elseif(isset($conditions['end_time']) && !empty($conditions['end_time'])){
                $lists->where('log.created_at','<',$conditions['end_time']);
            }
        }
        $lists = $lists->select(array('log.*','platform.name as source_name'))
            ->orderBy('log.created_at','desc')
            ->paginate($pageSize,['*'],'page',$page);
        return $lists;
    }


    /**
     * Todo:: 全部需要的表
     * @param array $conditions 条件
     * @param array $select 查询结果
     * @return \Illuminate\Database\Query\Builder|mixed
     */
    private function allTable($conditions=[],$select=[]){
        $lists = DB::table($this->table)
            ->leftJoin('platform',"{$this->table}.source_id",'=','platform.id')
            ->select(array(
                "{$this->table}.*",
                "platform.account","platform.name","platform.domain_name"
            ));
        $tempTable = array(1=>$this->table,2=>'platform');
        $lists = $this->allWhere($lists,$conditions,$tempTable);
        $tables = $this->tables();
        unset($tables[0]);
        foreach ($tables as $key=>$val){
            $rowTable = DB::table($val)
                ->leftJoin('platform',"{$val}.source_id",'=','platform.id')
                ->select(array(
                    "{$val}.*",
                    "platform.account","platform.name","platform.domain_name"
                ));
            $tempTable = array(1=>$val,2=>'platform');
            $rowTable = $this->allWhere($rowTable,$conditions,$tempTable);
            $lists->union($rowTable);
        }
        return $lists;
    }

    /**
     * Todo:: 全部资产日志 公共判断条件
     * @param $lists
     * @param $conditions 条件
     * @param $tempTable 表名
     * @return mixed
     */
    private function allWhere($lists,$conditions,$tempTable){
        if (isset($conditions['user_id']) && !empty($conditions['user_id'])) {
            $lists->where("{$tempTable[1]}.user_id", $conditions['user_id']);
        }
        if (isset($conditions['type']) && !empty($conditions['type'])) {
            $lists->where("{$tempTable[1]}.type", $conditions['type']);
        }
        if (isset($conditions['ip']) && !empty($conditions['ip'])) {
            $lists->where("{$tempTable[1]}.ip", $conditions['ip']);
        }
        if (isset($conditions['source_id']) && !empty($conditions['source_id'])) {
            $lists->where("{$tempTable[1]}.source_id", $conditions['source_id']);
        }
        if (isset($conditions['start_time']) && !empty($conditions['start_time']) && isset($conditions['end_time']) && !empty($conditions['end_time'])) {
            $lists->whereBetween("{$tempTable[1]}.created_at", [$conditions['start_time'],$conditions['end_time']]);
        }else{
            if(isset($conditions['start_time']) && !empty($conditions['start_time'])){
                $lists->where("{$tempTable[1]}.created_at",'>',$conditions['start_time']);
            }elseif(isset($conditions['end_time']) && !empty($conditions['end_time'])){
                $lists->where("{$tempTable[1]}.created_at",'<',$conditions['end_time']);
            }
        }
        return $lists;
    }


    /**
     * Todo:: 全部资产日志列表
     * @param array $conditions
     * @param int $page
     * @param int $pageSize
     * @return \Illuminate\Database\Query\Builder|mixed
     */
    public function allLists($conditions=[],$page=1,$pageSize=20){
        $lists = $this->allTable($conditions);
        $lists = $lists->orderBy('created_at','desc')->paginate($pageSize,['*'],'page',$page);
        return $lists;
    }

}
